package com.itheima.service.mongo.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.Sound;
import com.itheima.service.mongo.SoundService;
import com.itheima.util.ConstantUtil;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;

@DubboService
public class SoundServiceImpl implements SoundService {

    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 保存语音
     * @param sound
     */
    @Override
    public void save(Sound sound) {
        mongoTemplate.save(sound);
    }

    /**
     * 查询发送语音条数
     * @param date
     * @param userId
     * @return
     */
    @Override
    public Integer findNum(String date, Long userId) {
        //1.创建查询条件
        Query query = new Query(Criteria.where("date").is(date)
                .and("userId").is(userId));
        //2.查询用户当日发送语音的条数
        Integer count = Math.toIntExact(mongoTemplate.count(query, Sound.class));

        return count;
    }

    /**
     * 获取一条随机的语音
     * @param userId
     * @return
     */
    @Override
    public Sound findOneSound(Long userId) {
        //1.查询一条随机的语音
        //1.1.查询最近7天的语音总条数,但是要排除自己发送的语音
        String date = DateUtil.offsetDay(new Date(), -7).toDateStr();//设置一个过去7天的时间;
        Query query = new Query(Criteria.where("userId").ne(userId).and("date").gt(date));
        //1.2.查询有多少条数据
        long count = mongoTemplate.count(query, Sound.class);
        if (count == 0){
            //1.3如果没有合适的数据则查询所有数据
            query = new Query(Criteria.where("userId").ne(userId));
            count = mongoTemplate.count(query,Sound.class);
            if (count == 0){
                //1.4如果数据表中没有语音,则返回一个null
                return null;
            }
        }
        //1.5根据count值取随机数;
        int random = RandomUtil.randomInt(0, (int) count);
        //1.6根据随机数取语音
        query=query.skip(random).limit(1);
        Sound sound = mongoTemplate.findOne(query, Sound.class);
        //2.将这条语音存储到我的语音表中;
        mongoTemplate.save(sound, ConstantUtil.SOUND_MINE+userId);
        //3.将这条语音记录在全体语音表中删除;
        mongoTemplate.remove(sound);
        //4.将这条语音返回到前端
        return sound;
    }

    /**
     * 查询接收语音的剩余条数
     * @param date
     * @return
     */
    @Override
    public Integer remainingTimes(String date,Long userId) {
        //1.创建同一天的查询条件
        Query query = new Query(Criteria.where("date").is(date));
        //2.查询我的语音表中的今日语音记录数
        long count = mongoTemplate.count(query, ConstantUtil.SOUND_MINE + userId);
        //3.计算剩余次数,返回结果
        Integer remainingTimes = Math.toIntExact(5 - count);

        return remainingTimes;
    }
}
